<template>
  <Form class="xtx-form" ref="uForm" :validation-schema="mySchema" autocomplete="off" v-slot="{errors}">
    <div class="user-info">
      <img :src="avatar" />
      <p>Hi，{{nickname}} 欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~</p>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field :class="{err:errors.mobile}" name="mobile" v-model="form.mobile" class="input" type="text" placeholder="绑定的手机号" />
      </div>
      <div class="error" v-if="errors.mobile">{{errors.mobile}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field :class="{err:errors.code}" name="code" v-model="form.code" class="input" type="text" placeholder="短信验证码" />
        <span class="code" @click="send()">{{time? time + "秒重新发送":"发送验证码"}}</span>
      </div>
      <div class="error" v-if="errors.code">{{errors.code}}</div>
    </div>
    <a @click="submit()" href="javascript:;" class="submit">立即绑定</a>
  </Form>
</template>

<script>
import QC from 'qc'
import { reactive, ref } from 'vue-demi'
import { Form, Field } from 'vee-validate'
import schema from '@/utils/vee-validate-schema'
import { useIntervalFn } from '@vueuse/shared'
import { userQQBindCode, userQQBindLogin } from '@/api/user'
import Message from '@/components/library/message'
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'

export default {
  name: 'CallbackBind',
  components: {
    Form, Field
  },
  props: {
    unionId: {
      type: String,
      default: ''
    }
  },
  setup (props) {
    const store = useStore()
    const route = useRoute()
    const router = useRouter()
    // 获取qq头像昵称
    const nickname = ref(null)
    const avatar = ref(null)
    if (props.unionId) {
      QC.api('get_user_info').success(res => {
        nickname.value = res.data.nickname
        avatar.value = res.data.figureurl_1
      })
    }
    // 校验规则数据
    const form = reactive({
      mobile: '13666666666',
      code: null
    })
    // 校验规则对象
    const mySchema = {
      mobile: schema.mobile,
      code: schema.code
    }
    // 发送验证码
    // 倒计时定时器
    const time = ref(0)
    const { pause, resume } = useIntervalFn(() => {
      time.value--
      if (time.value <= 0) {
        pause() // 清除定时器
      }
    }, 1000, false)
    const uForm = ref(null)
    const send = async () => {
      const valid = schema.mobile(form.mobile)
      if (valid === true) {
        if (time.value > 0) return
        await userQQBindCode(form.mobile).then(res => {
          Message({ type: 'success', text: '发送成功' })
          time.value = 60
          resume() // 开启倒计时
        }).catch(e => {
          Message({ type: 'error', text: e.response.data.message || '发送失败' })
        })
      } else {
        uForm.value.setFieldError('mobile', valid)
      }
    }
    // 立即绑定
    const submit = () => {
      const valid = uForm.value.validate()
      if (valid) {
        userQQBindLogin({ unionId: props.unionId, ...form }).then(res => {
          store.commit('user/setUser', res.result)
          store.dispatch('cart/merageCart').then(() => {
            router.push(route.query.redirectUrl || '/')
            Message({ type: 'success', text: '登录成功' })
          })
        }).catch(e => {
          Message({ type: 'error', text: e.response.data.message || '登录失败' })
        })
      }
    }
    return { nickname, avatar, form, mySchema, send, uForm, time, submit }
  }
}
</script>

<style scoped lang='less'>
.user-info {
    width: 320px;
    height: 70px;
    margin: 0 auto;
    display: flex;
    background: #f2f2f2;
    align-items: center;
    padding: 0 10px;
    margin-bottom: 25px;
    img {
      background: #f2f2f2;
      width: 50px;
      height: 50px;
    }
    p {
      padding-left: 10px;
    }
  }
  .code {
    position: absolute;
    right: 0;
    top: 0;
    line-height: 50px;
    width: 90px;
    color: #999;
    &:hover {
      cursor: pointer;
    }
  }
</style>
